package com.wpzf.ndhc.controller;

import com.alibaba.fastjson.JSONObject;
import com.wpzf.common.core.utils.ServletUtils;
import com.wpzf.common.core.web.domain.AjaxResult;
import com.wpzf.common.log.annotation.Log;
import com.wpzf.common.log.enums.BusinessType;
import com.wpzf.common.security.service.TokenService;
import com.wpzf.ndhc.service.WpzfNdhcAppService;
import com.wpzf.system.api.model.LoginUser;
import com.wpzf.zxhc.utils.OBSDeleteUnits;
import com.wpzf.zxhc.utils.OBSUploadUnits;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/wpzfndhcapp")
public class WpzfNdhcAPPController {

    @Autowired
    TokenService tokenService;

    @Autowired
    WpzfNdhcAppService wpzfNdhcAppService;

    /**
     * APP登录接口
     *
     * @param parm
     * @return
     */

    @Log(title = "APP登录接口", businessType = BusinessType.OTHER)
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public AjaxResult Login(@RequestBody Map<String, Object> parm) {
//        LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword());
//        return R.ok(tokenService.createToken(userInfo));
        return null;
    }

    /*获取批次号*/
    @Log(title = "获取批次号", businessType = BusinessType.OTHER)
    @RequestMapping(value = "/queryPch", method = RequestMethod.POST)
    public AjaxResult queryPch(@RequestBody Map<String, Object> parm) {
        List<Map<String, Object>> rest = wpzfNdhcAppService.queryPch(parm);
        if (rest != null) {
            return AjaxResult.success("获取批次号 成功", rest);
        }
        return AjaxResult.error("获取批次号 失败", -1);
    }

    /*区县列表获取接口*/
    @Log(title = "区县列表获取接口", businessType = BusinessType.OTHER)
    @RequestMapping(value = "/queryXzqdmList", method = RequestMethod.POST)
    public AjaxResult queryXzqdmList(@RequestBody Map<String, Object> parm) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        parm.put("xzqdm", loginUser.getSysUser().getXzqdm());
        List<Map<String, Object>> rest = wpzfNdhcAppService.queryXzqdmList(parm);
        Integer cnt = wpzfNdhcAppService.queryXzqdmListCount(parm);
        if (rest != null) {
            return AjaxResult.success("区县列表获取接口 成功", rest, cnt);
        }
        return AjaxResult.error("区县列表获取接口 失败", -1);
    }

    /*地块列表获取接口*/
    @Log(title = "地块列表获取接口", businessType = BusinessType.OTHER)
    @RequestMapping(value = "/queryDkTaskList", method = RequestMethod.POST)
    public AjaxResult queryDkTaskList(@RequestBody Map<String, Object> parm) {
        List<Map<String, Object>> rest = wpzfNdhcAppService.queryDkTaskList(parm);
        Integer cnt = wpzfNdhcAppService.queryDkTaskListCount(parm);
        if (rest != null) {
            return AjaxResult.success("区县列表获取接口 成功", rest, cnt);
        }
        return AjaxResult.error("区县列表获取接口 失败", -1);
    }

    /**
     * 获取所有项目信息
     *
     * @param parm
     * @return
     */
    @Log(title = "获取所有项目信息", businessType = BusinessType.OTHER)
    @RequestMapping(value = "/queryProjectList", method = RequestMethod.POST)
    public AjaxResult queryProjectList(@RequestBody Map<String, Object> parm) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        parm.put("xzqdm", loginUser.getSysUser().getXzqdm());
        List<Map<String, Object>> rest = wpzfNdhcAppService.queryProjectList(parm);
        Integer cnt = wpzfNdhcAppService.queryProjectListCount(parm);
        if (rest != null) {
            return AjaxResult.success("获取所有项目信息 成功", rest, cnt);
        }
        return AjaxResult.error("获取所有项目信息 失败", -1);
    }

    /**
     * 获取项目下所有任务信息
     *
     * @param parm
     * @return
     */
    @Log(title = "获取项目下所有任务信息", businessType = BusinessType.OTHER)
    @RequestMapping(value = "/queryTaskList", method = RequestMethod.POST)
    public AjaxResult queryTaskList(@RequestBody Map<String, Object> parm) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        parm.put("xzqdm", loginUser.getSysUser().getXzqdm());
        List<Map<String, Object>> rest = wpzfNdhcAppService.queryTaskList(parm);
        Integer cnt = wpzfNdhcAppService.queryTaskListCount(parm);
        if (rest != null) {
            return AjaxResult.success("获取项目下所有任务信息 成功", rest, cnt);
        }
        return AjaxResult.error("获取项目下所有任务信息 失败", -1);
    }

    /**
     * 获取任务下所有图斑信息
     *
     * @param parm
     * @return
     */
    @Log(title = "获取任务下所有图斑信息", businessType = BusinessType.OTHER)
    @RequestMapping(value = "/queryTbList", method = RequestMethod.POST)
    public AjaxResult queryTbList(@RequestBody Map<String, Object> parm) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        parm.put("xzqdm", loginUser.getSysUser().getXzqdm());
        List<Map<String, Object>> rest = wpzfNdhcAppService.queryTbList(parm);
        Integer cnt = wpzfNdhcAppService.queryTbListCount(parm);
        if (rest != null) {
            return AjaxResult.success("获取任务下所有图斑信息 成功", rest, cnt);
        }
        return AjaxResult.error("获取任务下所有图斑信息 失败", -1);
    }

    /*图斑详情*/
    @Log(title = "图斑详情接口", businessType = BusinessType.OTHER)
    @RequestMapping(value = "/queryTbInfo", method = RequestMethod.POST)
    public AjaxResult queryTbInfo(@RequestBody Map<String, Object> parm) {
        Map<String, Object> rest = wpzfNdhcAppService.queryTbInfo(parm);
        if (rest != null) {
            return AjaxResult.success("图斑详情接口 成功", rest);
        }
        return AjaxResult.error("图斑详情接口 失败", -1);
    }

    /*矢量范围接口*/
    @Log(title = "矢量范围接口", businessType = BusinessType.OTHER)
    @RequestMapping(value = "/queryWKT", method = RequestMethod.POST)
    public AjaxResult queryWKT(@RequestBody Map<String, Object> parm) {
        List<Map<String, Object>> rest = wpzfNdhcAppService.queryWKT(parm);
        if (rest != null) {
            return AjaxResult.success("矢量范围接口 成功", rest);
        }
        return AjaxResult.error("矢量范围接口 失败", -1);
    }

    /**
     * @param parm
     * @return
     */
    @Log(title = "APP提交", businessType = BusinessType.OTHER)
    @RequestMapping(value = "/saveTaskDetailAnnex", method = RequestMethod.POST)
    public AjaxResult saveTaskDetailAnnex(@RequestBody Map<String, Object> parm) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        parm.put("username", loginUser.getUsername());
        Integer rest = wpzfNdhcAppService.saveTaskDetailAnnex(parm);
        if (rest > 0) {
            return AjaxResult.success("APP提交 成功", rest);
        }
        return AjaxResult.error("APP提交 失败", -1);
    }

    /**
     * 文件上传
     *
     * @param file
     * @param uuid
     * @param jcbh
     * @param pch
     * @param xzqdm
     * @return
     */
    @Log(title = "文件上传", businessType = BusinessType.OTHER)
    @Transactional
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    public AjaxResult uploadFile(@RequestParam(value = "file") MultipartFile file,
                                 @RequestParam(value = "uuid") String uuid,
                                 @RequestParam(value = "jcbh") String jcbh,
                                 @RequestParam(value = "pch") String pch,
                                 @RequestParam(value = "xzqdm") String xzqdm) {
        try {
            if (file == null) {
                return AjaxResult.error("请选择需要上传的文件");
            } else {
                if (!file.isEmpty()) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("jcbh", jcbh);
                    map.put("pch", pch);
                    map.put("xzqdm", xzqdm);
                    map.put("uuid", uuid);
                    Map<String, Object> taskDetailAnnex = wpzfNdhcAppService.getTaskDetailAnnex(map);
                    if (taskDetailAnnex != null) {
                        Integer rest = 0;

                        // 获取文件原本的名字
                        String originName = file.getOriginalFilename();
                        // 判断文件是否是pdf文件
//        Set<String> set = new HashSet<>();
//        set.add(".pdf");
//        set.add(".doc");
//        set.add(".docx");
                        // 取出文件的后缀
                        int count = 0;
                        for (int i = 0; i < originName.length(); i++) {
                            if (originName.charAt(i) == '.') {
                                count = i;
                                break;
                            }
                        }
                        String endName = originName.substring(count); //取出文件类型
                        String fileType = originName.substring(count + 1); //文件类型
//        if (!set.contains(endName)) {
//            return new String("上传的文件类型错误,只能上传pdf,doc,docx类型的文件");
//        }
                        // 创建保存路径
                        String savePath = System.getProperty("user.dir") + "\\" + "appFiles" + "\\" + pch + "\\" + xzqdm + "\\" + jcbh;
                        // 保存文件的文件夹
                        File folder = new File(savePath);
                        // 判断路径是否存在,不存在则自动创建
                        if (!folder.exists()) {
                            folder.mkdirs();
                        }
                        String saveName = originName;

                        //文件存到本地
                        file.transferTo(new File(folder, saveName));
                        //文件地址
                        String filePath = savePath + "\\" + saveName;

                        String OBSAddress = "app" + "/" + pch + "/" + xzqdm + "/" + jcbh + "/" + saveName;
                        String log = OBSUploadUnits.OBSUpload(OBSAddress, filePath);
                        if ("success".equals(log)) {
                            String fj = "https://obs-top.obs.cn-north-1.myhuaweicloud.com/" + OBSAddress;
                            map.put("fj", fj);
                            rest = wpzfNdhcAppService.updateFjInfo(map);
                        } else {
                            return AjaxResult.error("OBS文件上传失败");
                        }
                        deleteFolder(folder);
                        if (rest > 0) {
                            return AjaxResult.success("文件上传成功");
                        }
                    } else {
                        return AjaxResult.error("信息不存在");
                    }
                }
                return AjaxResult.error("文件上传失败");
            }
        } catch (Exception ex) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("上传文件异常，请联系管理员" + ex);
        }
    }

    public static void deleteFolder(File folder) {
        if (folder.isDirectory()) {
            File[] files = folder.listFiles();
            if (files != null) {
                for (File file : files) {
                    deleteFolder(file);
                }
            }
        }
        folder.delete();
    }

    /**
     * 删除文件
     *
     * @param file
     * @param jcbh
     * @param pch
     * @param xzqdm
     * @param uuid
     * @return
     */
    @RequestMapping(value = "/deleteFile", method = RequestMethod.POST)
    public AjaxResult deleteFile(@RequestParam(value = "file") MultipartFile file,
                                 @RequestParam(value = "jcbh") String jcbh,
                                 @RequestParam(value = "pch") String pch,
                                 @RequestParam(value = "xzqdm") String xzqdm,
                                 @RequestParam(value = "uuid") String uuid) {
        try {
            if (file == null) {
                return AjaxResult.error("请选择需要删除的文件");
            } else {
                if (!file.isEmpty()) {
                    String saveName = file.getOriginalFilename();
                    Map<String, Object> map = new HashMap<>();
                    map.put("jcbh", jcbh);
                    map.put("pch", pch);
                    map.put("xzqdm", xzqdm);
                    String OBSAddress = "app" + "/" + pch + "/" + xzqdm + "/" + jcbh + "/" + saveName;
                    OBSDeleteUnits.OBSDelete(OBSAddress);
                }
            }
            return AjaxResult.success("文件删除成功");
        } catch (Exception ex) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("删除文件异常，请联系管理员" + ex);
        }
    }

    /*1.7举证结果信息上传*/
//    @Log(title = "1.7举证结果信息上传", businessType = BusinessType.OTHER)

    /*1.8举证照片回显*/
//    @Log(title = "1.8举证照片回显", businessType = BusinessType.OTHER)

    /*1.9其他接口*/
//    @Log(title = "1.9其他接口", businessType = BusinessType.OTHER)


    /**
     * 文件上传
     *
     * @param file
     * @param jcbh
     * @param xzqdm
     * @return
     */
    @Log(title = "文件上传", businessType = BusinessType.OTHER)
    @Transactional
    @RequestMapping(value = "/uploadOBSFile", method = RequestMethod.POST)
    public AjaxResult uploadOBSFile(@RequestParam(value = "file") MultipartFile file,
                                    @RequestParam(value = "jcbh") String jcbh,
                                    @RequestParam(value = "xzqdm") String xzqdm,
                                    @RequestParam(value = "pch") String pch) {
        try {
            if (file == null) {
                return AjaxResult.error("请选择需要上传的文件");
            } else {
                if (!file.isEmpty()) {

                    // 获取文件原本的名字
                    String originName = file.getOriginalFilename();
                    // 判断文件是否是pdf文件
//        Set<String> set = new HashSet<>();
//        set.add(".pdf");
//        set.add(".doc");
//        set.add(".docx");
                    // 取出文件的后缀
                    int count = 0;
                    for (int i = 0; i < originName.length(); i++) {
                        if (originName.charAt(i) == '.') {
                            count = i;
                            break;
                        }
                    }
                    String endName = originName.substring(count); //取出文件类型
                    String fileType = originName.substring(count + 1); //文件类型
//        if (!set.contains(endName)) {
//            return new String("上传的文件类型错误,只能上传pdf,doc,docx类型的文件");
//        }
                    // 创建保存路径
                    String savePath = System.getProperty("user.dir") + "\\" + "appNdhcFiles" + "\\" + pch + "\\" + xzqdm + "\\" + jcbh;
                    // 保存文件的文件夹
                    File folder = new File(savePath);
                    // 判断路径是否存在,不存在则自动创建
                    if (!folder.exists()) {
                        folder.mkdirs();
                    }
                    String saveName = originName;

                    //文件存到本地
                    file.transferTo(new File(folder, saveName));
                    //文件地址
                    String filePath = savePath + "\\" + saveName;

                    String OBSAddress = "appNdhc" + "/" + pch + "/" + xzqdm + "/" + jcbh + "/" + saveName;
                    String log = OBSUploadUnits.OBSUpload(OBSAddress, filePath);
                    deleteFolder(folder);
                    Map<String, Object> rest = new HashMap<>();
                    if ("success".equals(log)) {
                        String fj = "https://obs-top.obs.cn-north-1.myhuaweicloud.com/" + OBSAddress;
                        rest.put("fj", fj);
                        return AjaxResult.success("文件上传成功", rest);
                    } else {
                        return AjaxResult.error("OBS文件上传失败", rest);
                    }
                }
                return AjaxResult.error("文件上传失败");
            }
        } catch (Exception ex) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("上传文件异常，请联系管理员" + ex);
        }
    }

    /**
     * 删除文件
     *
     * @param file
     * @param jcbh
     * @param xzqdm
     * @return
     */
    @RequestMapping(value = "/deleteOBSFile", method = RequestMethod.POST)
    public AjaxResult deleteOBSFile(@RequestParam(value = "file") MultipartFile file,
                                    @RequestParam(value = "jcbh") String jcbh,
                                    @RequestParam(value = "xzqdm") String xzqdm,
                                    @RequestParam(value = "pch") String pch) {
        try {
            if (file == null) {
                return AjaxResult.error("请选择需要删除的文件");
            } else {
                if (!file.isEmpty()) {
                    String saveName = file.getOriginalFilename();
                    String OBSAddress = "appNdhc" + "/" + pch + "/" + xzqdm + "/" + jcbh + "/" + saveName;
                    OBSDeleteUnits.OBSDelete(OBSAddress);
                }
            }
            return AjaxResult.success("文件删除成功");
        } catch (Exception ex) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("删除文件异常，请联系管理员" + ex);
        }
    }


    /**
     * @param parm
     * @return
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public AjaxResult save(@RequestBody Map<String, Object> parm) {
        JSONObject s = new JSONObject(parm);
        System.out.println(s.toJSONString());
        System.out.println(parm.get("fj"));
        Integer rest = wpzfNdhcAppService.save(parm);
        if (rest > 0) {
            return AjaxResult.success("保存 成功", rest);
        }
        return AjaxResult.error("保存 失败", -1);
    }

    /**
     * @param parm
     * @return
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public AjaxResult delete(@RequestBody Map<String, Object> parm) {
        Integer rest = wpzfNdhcAppService.delete(parm);
        if (rest > 0) {
            return AjaxResult.success("删除 成功", rest);
        }
        return AjaxResult.error("删除 失败", -1);
    }

}
